package study.nosql.redis.support.redis;

import cn.hutool.core.thread.ExecutorBuilder;
import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Configuration
public class RedisListenerConfig {

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory factory) {
        //监听容器
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);

        //任务线程池
        ThreadFactory f1 = ThreadUtil.createThreadFactoryBuilder()
                .setNamePrefix("My-Redis-Task-").build();
        ThreadPoolExecutor p1 = ExecutorBuilder.create()
                .setCorePoolSize(2)
                .setThreadFactory(f1)
                .build();
        container.setTaskExecutor(p1);
        //订阅线程池
        ThreadFactory f2 = ThreadUtil.createThreadFactoryBuilder()
                .setNamePrefix("My-Redis-Sub-").build();
        ThreadPoolExecutor p2 = ExecutorBuilder.create()
                .setCorePoolSize(2)
                .setThreadFactory(f2)
                .build();
        container.setSubscriptionExecutor(p2);


        //（★）新增订阅
        //container.addMessageListener(redisMsgListener, new ChannelTopic("topic"));
        //container.addMessageListener(redisKeyspaceListener, new PatternTopic("__keyspace@*"));
        //（★）对频道内容进行序列化解析（特别注意：发布的时候需要设置序列化；订阅方也需要设置序列化）
        //container.setTopicSerializer();

        return container;
    }
}
